<template>
    <div class="marketing_seckill_list">
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="活动名称" prop="activityName">
                            <el-input v-model="form.activityName" clearable placeholder="请输入活动名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="活动状态" prop="activityStatus">
                            <el-select v-model="form.activityStatus" clearable placeholder="请选择状态">
                                <el-option
                                    v-for="item in activityStatusList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain @click="resetHandler">清空</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-row>
            <el-col class="zw-table-btns">
                <el-button type="primary" v-auth="'seckill_list:creat'" @click="ceateHanlder"> 新增秒杀 </el-button>
            </el-col>
        </el-row>
        <el-table :data="tableList" stripe>
            <el-table-column label="活动名称" show-overflow-tooltip prop="activityName" min-width="200px">
                <template v-slot="{ row }">
                    <div class="custom-el-link">
                        <span @click="goDetailHandler(row)">{{ row.activityName }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="活动时间" prop="startTime" width="200">
                <template v-slot="{ row }"> {{ row.activityStartTime }}至<br />{{ row.activityEndTime }} </template>
            </el-table-column>
            <el-table-column label="活动商品" show-overflow-tooltip min-width="180" prop="">
                <template v-slot="{ row }">
                    <div class="flex name-flex">
                        <img :src="row.coverImg" />
                        <div class="warp">
                            {{ row.goodsName }}
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="秒杀价（元）" prop="seckillGoodsMinPrice" width="110px">
                <template v-slot="{ row }">
                    <div v-if="row.seckillGoodsMinPrice === row.seckillGoodsMaxPrice">
                        {{ floatDivide(row.seckillGoodsMinPrice, 100) }}
                    </div>
                    <div v-else>
                        {{ floatDivide(row.seckillGoodsMinPrice, 100) }} ~
                        {{ floatDivide(row.seckillGoodsMaxPrice, 100) }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="原价（元）" prop="goodsMinPrice" width="95">
                <template v-slot="{ row }">
                    <div v-if="row.goodsMinPrice === row.goodsMaxPrice">
                        {{ floatDivide(row.goodsMinPrice, 100) }}
                    </div>
                    <div v-else>
                        {{ floatDivide(row.goodsMinPrice, 100) }} ~ {{ floatDivide(row.goodsMaxPrice, 100) }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="秒杀剩余库存" width="120" prop="spikeStockSurplus"></el-table-column>
            <el-table-column label="活动状态" prop="statusName"> </el-table-column>
            <el-table-column fixed="right" label="操作" width="240">
                <template v-slot="{ row }">
                    <div class="btns">
                        <el-button
                            size="small"
                            v-auth="'seckill_list:edit'"
                            v-show="[1, 2].includes(row.status)"
                            @click="editHandler(row)">
                            编辑
                        </el-button>
                        <el-popover
                            popper-class="custom-skill-popover not-close"
                            placement="top"
                            width="400"
                            :visible="row.id === openPopoverId">
                            <template #reference>
                                <span>
                                    <el-button
                                        size="small"
                                        v-click-outside="onClickOutside"
                                        v-auth="'seckill_list:spread'"
                                        v-show="[1, 2].includes(row.status)"
                                        @click="spreadHandler(row)">
                                        推广
                                    </el-button>
                                </span>
                            </template>
                            <SpreadBox
                                v-if="row.id === openPopoverId"
                                :path="path"
                                :params="params"
                                :downloadName="downloadName"
                                :popoverFn="popoverVisibleHandler" />
                        </el-popover>
                        <el-button size="small" @click="dataViewHandler(row)"> 数据 </el-button>
                        <el-popconfirm hide-icon @confirm="changeStatusActivityHandler(row, 1)" title="确定结束?">
                            <template #reference>
                                <el-button
                                    v-auth="'seckill_list:end'"
                                    v-show="[1, 2].includes(row.status)"
                                    size="small">
                                    结束
                                </el-button>
                            </template>
                        </el-popconfirm>
                        <el-popconfirm hide-icon @confirm="changeStatusActivityHandler(row, 2)" title="确定删除?">
                            <template #reference>
                                <el-button
                                    v-auth="'seckill_list:delete'"
                                    v-show="[3].includes(row.status)"
                                    size="small">
                                    删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 15px">
            <Pagination
                :total="totalCount"
                :page-size="form.perPage"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
    </div>
</template>

<script setup name="seckillList">
import { ref, reactive, onMounted, onActivated, computed } from 'vue';
import Pagination from '@/components/Pagination.vue';
import storage from '@/commons/storage';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, floatDivide, format, downloadImgHandler } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { ClickOutside as vClickOutside } from 'element-plus';
import SpreadBox from '@/components/SpreadBox.vue';

const router = useRouter();
let openPopoverId = ref('');

const activityStatusList = reactive(packSelectObjUtil(constants.SECKILL_STATUS_OPTIONS));

const totalCount = ref(0);
const form = reactive({
    page: 1,
    perPage: 10,
    activityName: null,
    choiceSpike: 1,
    activityStatus: null
});
let tableList = reactive([]);
const formRef = ref(null);

const qrCodeUrl = ref('');

/**
 * 分页查询
 */
const querySeckillListHandler = async () => {
    const res = await request('seckillListServ', form);
    const list = res.data.list || [];
    tableList.length = 0;
    const row = {
        goodsName: '',
        goodsImg: '',
        spikeStockSurplus: '',
        goodsMinPrice: '',
        goodsMaxPrice: '',
        seckillGoodsMaxPrice: '',
        seckillGoodsMinPrice: '',
        status: '',
        statusName: ''
    };
    list.forEach(x => {
        row.goodsName = x.activityGoods.find(x => x.goodsName)?.goodsName || '';
        row.goodsImg = x.activityGoods.find(x => x.goodsImg)?.goodsImg || '';
        row.statusName = x.activityStatusName.realStatusName;
        row.status = x.activityStatusName.realStatus;
        // 剩余库存
        let stockArr = Array.from(x.activityGoods, e => e.spikeStockSurplus);
        row.spikeStockSurplus =
            stockArr.length > 0
                ? stockArr.reduce((a, b) => {
                      return a + b;
                  })
                : '';
        const priceArr = Array.from(
            Array.from(x.activityGoods, e => e.skuAttrInfo),
            t => t.skuPrice
        );
        const seckillPriceArr = Array.from(x.activityGoods, e => e.spikePrice);
        // 商品原价
        row.goodsMinPrice = priceArr.sort((a, b) => a - b)[0];
        row.goodsMaxPrice = priceArr.sort((a, b) => a - b)[priceArr.length - 1];
        // 商品秒杀价
        row.seckillGoodsMinPrice = seckillPriceArr.sort((a, b) => a - b)[0];
        row.seckillGoodsMaxPrice = seckillPriceArr.sort((a, b) => a - b)[seckillPriceArr.length - 1];
        tableList.push(Object.assign({}, row, x));
    });
    totalCount.value = res.data.totalCount;
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    querySeckillListHandler();
};

/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    querySeckillListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    querySeckillListHandler();
};

const ceateHanlder = () => {
    router.push('/marketing/seckill/create');
};

const editHandler = ({ id }) => {
    router.push(`/marketing/seckill/edit?id=${id}`);
};

const goDetailHandler = row => {
    router.push(`/marketing/seckill/detail?id=${row.id}&tab=2`);
};

const dataViewHandler = row => {
    router.push(`/marketing/seckill/detail?id=${row.id}&tab=1`);
};

const popoverVisibleHandler = () => {
    openPopoverId.value = null;
};
/**
 * 显示小程序推广码
 * @param {*} row
 */
let path = ref();
let params = ref();
let downloadName = ref();
const spreadHandler = async row => {
    path.value = 'pages-cart/good/index';
    params.value = `goodsId=${row.goodsId}&goodsNo=${row.goodsNo}&shopId=${storage.get('ZW-SHOPID')}&activityId=${
        row.id
    }`;
    downloadName.value = row?.activityName;
    openPopoverId.value = row.id;
};

// 点击popover外部
const onClickOutside = el => {
    if (
        el?.path?.every(
            item => !item?.className || !item?.className?.includes || !item?.className?.includes('not-close')
        )
    ) {
        openPopoverId.value = '';
    }
};

const downloadIamge = row => {
    const url = qrCodeUrl.value;
    const fileName = row.activityName;
    downloadImgHandler(url, fileName);
};

const changeStatusActivityHandler = (row, status) => {
    const requestName = status === 2 ? 'deteleSeckillServ' : 'endSeckillServ';
    request(requestName, { id: row.id }).then(res => {
        ElMessage.success(`操作成功`);
        searchHandler();
    });
};

onMounted(() => {
    searchHandler();
});
</script>

<style lang="scss">
.custom-skill-popover {
    padding: 0 !important;
}
</style>
<style lang="scss" scoped>
.marketing_seckill_list {
    :deep {
        .el-table {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
            .el-button--small {
                font-size: 12px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
                border: 1px solid #eaeaea;
            }
            .el-button--small + .el-button--small {
                margin-left: 8px;
            }
        }
        .el-tabs__nav-wrap {
            margin-bottom: -15px;
            &::after {
                height: 0;
            }
        }
        .el-table .el-table__cell {
            padding: 20px 0;
        }

        .el-table th.el-table__cell {
            padding: 12px 0;
        }

        .el-table th.el-table__cell {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #33302d;
        }
    }
    .custom-el-link {
        color: rgb(255, 107, 0);
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        span {
            cursor: pointer;
            &:hover {
                text-decoration: underline;
            }
        }
    }
    .flex {
        display: flex;
        line-height: 14px;
        img {
            width: 36px;
            height: 36px;
            min-width: 36px;
            margin-right: 12px;
        }
    }
    .el-table_1_column_3 .cell {
        margin: -4px 0;
    }
    .warp {
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        word-break: break-all;
        white-space: pre-wrap;
        line-height: 18px;
    }
    .btns {
        display: flex;
        overflow: hidden;
        flex-wrap: wrap;
        .el-button + .el-button {
            margin-left: 0;
        }
        .el-button {
            margin-bottom: 6px;
            margin-right: 6px;
        }
    }
}
</style>
